package com.xiaofan.mq.order;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.crypto.Data;
import java.nio.charset.StandardCharsets;

/**
 * 订单超时未付款消息提供者
 * @author 晓帆
 * @version 1.0
 *
 **/
@Component
@Slf4j
public class DelayOrderProducer {
    private DefaultMQProducer delayOrderProducer;
    @PostConstruct
    public void init(){
        delayOrderProducer=new DefaultMQProducer("delay_order_producer");
        delayOrderProducer.setNamesrvAddr("127.0.0.1:9876");
        try {
            delayOrderProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendMessage(String orderId){
        try {
            byte[] bytes = orderId.getBytes(StandardCharsets.UTF_8);
            Message message = new Message("delay_order_topic",bytes);
            message.setDelayTimeLevel(16);
            SendResult send = delayOrderProducer.send(message);
            System.out.println(send.getSendStatus());
            if (SendStatus.SEND_OK.equals(send.getSendStatus())){
                return true;
            }
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}
